import math
import random
from concurrent.futures import ThreadPoolExecutor
from faker import Faker

from pandas import DataFrame
import pandas as pd

from examples.plugin.common import timer


@timer
def r(param_dict: dict) -> DataFrame:
    rows = param_dict["rows"]
    columns = param_dict["columns"]
    randoms = param_dict["randoms"]
    faker = Faker('zh-CN')
    list_map = []
    for i in range(rows):
        current_row = {}
        for column in columns:
            exec_str = "faker.{}()".format(column)
            result = eval(exec_str)
            current_row[column] = result
        for element in randoms:
            key = element["key"]
            values = element["values"]
            value = random.choice(values)
            current_row[key] = value

        list_map.append(current_row)
    df = pd.DataFrame(list_map)
    return df

@timer
def run(param_dict: dict) -> list:
    rows = param_dict["rows"]
    max_workers = 10
    num_tasks = range_num(rows,max_workers)
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        results = []
        futures = []
        for num in num_tasks:
            future = executor.submit(task, num,param_dict)
            futures.append(future)

        for future in futures:
            sub_row_list = future.result()
            results.extend(sub_row_list)

    df = pd.DataFrame(results)
    return df


def task(num: int, param_dict: dict) -> list:
    columns = param_dict["columns"]
    randoms = param_dict["randoms"]
    list_map = []
    faker = Faker('zh-CN')
    for i in range(num):
        current_row = {}
        for column in columns:
            exec_str = "faker.{}()".format(column)
            result = eval(exec_str)
            current_row[column] = result
        for element in randoms:
            key = element["key"]
            values = element["values"]
            value = random.choice(values)
            current_row[key] = value
        list_map.append(current_row)
    return list_map


def range_num(total_num: int, range_num: int):
    """将一个整数num均匀分为n等份，且保证分出的结果都为整数，如果不为整数，则向上取整，让最后一等分补充
       """
    if total_num <= 1000:
        return [total_num]
    number = math.ceil(total_num / range_num)
    num_list = []
    tmp_number = total_num
    for i in range(range_num):
        if i == range_num - 1:
            num_list.append(tmp_number)
        else:
            num_list.append(number)
        tmp_number = tmp_number - number
    return num_list


if __name__ == '__main__':
    print(range_num(900, 7))
